<template>
  <div class="custom-page">
    <div class="custom">
      <el-dialog v-if="dialog" :visible.sync="dialog" title="自定义页面" width="650px">
        <el-form ref="createInfo" :model="form" :rules="rules">
          <el-form-item :label-width="formLabelWidth" label="标题" prop="title">
            <el-input v-model="form.title" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="编辑类型">
            <el-radio v-model="form.editType" label="visualEditor">可视化编辑器</el-radio>
            <el-radio v-model="form.editType" label="HTMLEditor">HTML编辑器</el-radio>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="URL路径" prop="url">
            <el-input v-model="form.url" style="width:300px;"/>
            <br><span v-if="message" style="color: red">&nbsp;&nbsp;{{ message }}</span>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="模板">
            <el-select v-model="form.template">
              <el-option label="默认模版" value="default"/>
              <el-option label="无导航栏" value="noNav"/>
              <el-option label="空白页" value="noContent"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.editType === 'visualEditor'">
            <tinymce :height="200" :show="true" v-model="form.content"/>
          </el-form-item>
          <el-form-item v-if="form.editType === 'HTMLEditor'">
            <el-input
              v-model="form.content"
              :rows="4"
              type="textarea"
              style="height:200px;"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button type="primary" @click="saveInfo">确 定</el-button>
        </div>
      </el-dialog>
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="22">
          <el-select v-model="status" style="width:120px;" @change="handleFilter">
            <el-option
              v-for="item in options"
              :value="item.value"
              :key="item.value"
              :label="item.label"
            />
          </el-select>
          <el-input v-model="title" placeholder="关键词" style="width:220px;" @keyup.enter.native="handleFilter"/>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
        <el-col :span="2">
          <div style="width:100%;">
            <el-button
              type="primary"
              style="float:right;"
              @click="add()"
            >
              新增页面
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <subtable
      :table-label="customLabel"
      :table-data="customData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="button" :min-width="100" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            type="primary"
            @click="editDetail(scope.row)"
            @command="handleCommand($event,scope.row)"
          >编辑
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.status === 'unpublished' || scope.row.status === 'trash'" command="1">发布</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'trash'" command="2">永久删除</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'published'" command="3">移至回收站</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </subtable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
  </div>
</template>

<script>
import Subtable from '@/components/Eltable'
import Tinymce from '@/components/Tinymce'
import Pagination from '@/components/Pagination' // 分页组件
import { getPageManagementList, addPage, updatePage, deletePage } from '@/api/operate/pageManagement' // 数据接口
import { getTenantId, getUserId, getUserName } from '@/utils/auth'
export default {
  components: {
    Subtable,
    Tinymce,
    Pagination
  },
  data() {
    return {
      total: 0,
      currentpage: 1,
      pagesize: 10,
      reg: /^((https|http|ftp|rtsp|mms){1}(:\/\/){0,1})(([A-Za-z0-9-~]+)(\.([A-Za-z0-9-~])+)*\:([A-Za-z0-9-~]+))*(([A-Za-z0-9-~]+)\.)*([A-Za-z0-9-~\/])+((\![A-Za-z0-9-~]+\.[A-Za-z0-9-~]+)*)$/,
      message: 'URL路径必须以http开头!',
      customLabel: [
        {
          label: '标题', width: '', prop: 'title', isOpera: true
        }, {
          label: '页面地址', width: '', prop: 'url', isOpera: true
        }, {
          label: '类型', width: '', prop: 'typeStr'
        }, {
          label: '状态', width: '', prop: 'statusStr'
        }, {
          label: '发布时间/人', width: '', prop: 'msg'
        }
      ],
      customData: [],
      listFilter: [],
      activeName: '1',
      form: {
        title: '',
        type: 'page',
        editType: 'visualEditor',
        url: '',
        template: 'default',
        content: '',
        status: 'published',
        toolbar
      },
      title: '',
      status: '',
      dialog: false,
      radio: '1',
      formLabelWidth: '30%',
      options: [
        {
          label: '--所有状态--',
          value: ''
        },
        {
          label: '已发布',
          value: 'published'
        },
        {
          label: '未发布',
          value: 'unpublished'
        },
        {
          label: '回收站',
          value: 'trash'
        }
      ],
      rules: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    handleSizeChange(val) {
      console.log(val);
      this.currentpage = 1;
      this.pagesize = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentpage = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    editDetail(row) {
      this.form = Object.assign({}, row);
      this.dialog = true
    },
    handleFilter() {
      this.customData = this.listFilter.filter(item => {
        if (this.status && item.status !== this.status) return false;
        if (this.title && item.title.toLocaleLowerCase().indexOf(this.title.toLocaleLowerCase()) === -1) return false;
        return true
      });
      this.total = this.customData.length
    },
    clearParams() {
      this.status = '';
      this.title = '';
      this.getData()
    },
    getData() {
      getPageManagementList().then(response => {
        this.customData = response.data.items.filter(item => {
          if (item.tenantId !== getTenantId()) return false;
          return true
        });
        this.customData.map((item) => {
          if (item.status === 'published') item.statusStr = '已发布';
          if (item.status === 'unpublished') item.statusStr = '未发布';
          if (item.status === 'trash') item.statusStr = '回收站';
          if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '');
          item.msg = (item.createTimeStr ? item.createTimeStr : '') + '\n' + (item.userName ? item.userName : '');
          if (item.type === 'page') item.typeStr = '页面'
        });
        this.total = this.customData.length;
        this.listFilter = this.customData
      })
    },
    saveInfo() {
      console.log(this.form);
      this.$refs.createInfo.validate((valid) => {
        if (valid) {
          if (this.form.url && !this.reg.test(this.form.url)) {
            this.message = '输入的值并不是一个合法的网址，请重新输入！';
            return
          } else {
            this.message = ''
          }
          if (this.form.id) {
            updatePage(this.form).then(res => {
              this.$notify({
                title: '成功',
                message: '自定义页面修改成功',
                type: 'success',
                duration: 2000
              });
              this.getData()
            })
          } else {
            this.form.userId = getUserId();
            this.form.userName = getUserName();
            this.form.tenantId = getTenantId();
            addPage(this.form).then(res => {
              this.$notify({
                title: '成功',
                message: '新增自定义页面成功！',
                type: 'success',
                duration: 2000
              });
              this.getData()
            })
          }
          this.dialog = false
        }
      })
    },
    handleCommand(command, row) {
      if (command === '1') {
        row.status = 'published';
        updatePage(row).then(res => {
          this.$notify({
            title: '成功',
            message: '自定义页面修改成功！',
            type: 'success',
            duration: 2000
          });
          this.getData()
        })
      } else if (command === '2') {
        this.$confirm('确认要删除该自定义页面', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePage(row.id).then(res => {
            this.$notify({
              title: '成功',
              message: '自定义页面已删除',
              type: 'success',
              duration: 2000
            });
            this.getData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消'
          })
        })
      } else if (command === '3') {
        row.status = 'trash';
        updatePage(row).then(res => {
          this.$notify({
            title: '成功',
            message: '自定义页面已移至回收站！',
            type: 'success',
            duration: 2000
          });
          this.getData()
        })
      }
    },
    add(){
      this.dialog=true;
      this.form = {type: 'page', editType: 'visualEditor', template: 'default', status: 'published'}
    }
  }
}
</script>

<style lang="scss">
.custom-page {
  padding: 14px 20px;
  .custom {
    margin-top: 0;
    padding: 0;
    .el-dialog {
      border-radius: 10px;
    }
  }
  .el-table .cell{
    white-space: pre-wrap;
  }
  .addprogram {
    width: 100%;
    padding: 20px 0;
    .el-button {
      float: right;
    }
  }
}
</style>

